package com.gientech.madp.sm2.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.gientech.madp.sm2.service.SM4Service;
import com.gientech.madp.sm2.utils.R;
import com.gientech.madp.sm2.utils.SM4Util;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * @Author smile_ZhongXuan
 * @Date 2021/11/1 14:31
 * @Version 1.0
 */
@Service
@AllArgsConstructor
public class SM4ServiceImpl implements SM4Service {
    @Override
    public R encrypt(String security, JSONObject jsonObject) {
        if (StrUtil.isBlank(security)){
            return R.failed("加密秘钥不能为空！");
        }
        if (StrUtil.isBlank(jsonObject.toString())){
            return R.failed("加密内容体不能为空！");
        }
        String encryptEcb = null;
        try {
            encryptEcb = SM4Util.encryptDataECB(security, jsonObject.toString());
            System.out.println("SM4加密： " + encryptEcb);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return R.ok(encryptEcb);
    }

    @Override
    public R decrypt(String security, Map map) {
        String enString = map.get("enString").toString();
        if (StrUtil.isBlank(security)){
            return R.failed("解密秘钥不能为空！");
        }
        if (StrUtil.isBlank(enString)){
            return R.failed("解密内容体不能为空！");
        }
        String decryptEcb = null;
        try {
            decryptEcb = SM4Util.decryptDataECB(security, enString);
            System.out.println("SM4解密： " + decryptEcb);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return R.ok(JSONUtil.parseObj(decryptEcb),"SM4解密后的结果");
    }
}
